﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.DataProtection;

namespace Tax.API
{
    using Tax.Util;
    using Tax.Service;
    using Tax.Contract.IServices;
    using Tax.DataAccess.Models;

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.WithOrigins(Configuration.GetSection("CorsUrl").Get<string[]>())
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//for cookie
                });
            });

            services.AddEntityFrameworkSqlServer().AddDbContext<TaxationContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Taxation"))
                );

            #region use Redis for Session
            var redisConn = Configuration["WebConfig:Redis:Connection"];
            var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"];
            var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30);

            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn);
            services.AddDataProtection().PersistKeysToRedis(redis, "Tax-API");
            services.AddDistributedRedisCache(option =>
            {
                //redis ConnectionString
                option.Configuration = redisConn;
                option.InstanceName = redisInstanceName;
            }
            );
            #endregion

            RedisUtils.Register(redisConn);

            services.AddDistributedMemoryCache();
            services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped<ISecurityService, SecurityService>();
            services.AddScoped<IBusinessService, BusinessService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("any");
            app.UseStaticHttpContext();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseMvc();
        }
    }
}
